public with sharing class SendMessage {
    
   //public Account acc{get;set;}
   public List<MessageEntry> accLeftList{get;set;}
    public List<MessageEntry> accRightList{get;set;}
    public List<User> userList{get;set;}
    public User user{get;set;}   
    public String UserName{get;set;}
    //public String UserCity{get;set;}
    public Boolean SDisplay{get;set;} 
    public Boolean MDisplay{get;set;}
    public Message__c mhr{get;set;}
    public String Msg{get;set;}
    public List<SelectOption> channelList{get;set;} 
    public List<SelectOption> outletTypeList{get;set;}
    public String channelValue{get;set;}
    public String outletTypeValue{get;set;}
    public Boolean isCheck{get;set;}
    public Boolean isCheck2{get;set;}
    public Boolean controlIsDisplay{get;set;}
    public String errorMsg{get;set;}
    public String mainErrorMsg{get;set;}
    public List<SelectOption> MsgTypeList{get;set;}
    public String MsgTypeValue{get;set;}
    public List<SelectOption> KAAccountList{get;set;}//KA连锁客户下拉列表值
    public String KAAccountValue{get;set;}//KA连锁客户的值
    
    public List<SelectOption> RegionList{get;set;}
    public String RegionValue{get;set;}
    public String SubRegionValue{get;set;}
    public String AreaValue{get;set;}
    public String CityValue{get;set;}
    public User u;
    
   /* public String AlertMsg1{get;set;}
    public String AlertMsg2{get;set;}
    public String AlertMsg3{get;set;}
    public String AlertMsg4{get;set;}
    public String AlertMsg5{get;set;}*/
    //public Set<Id> ContactUserIdSet;
    
    public String FileName1{get;set;}
    public String FileName2{get;set;}
    public String FileName3{get;set;}
    public String FileName4{get;set;}
    public String FileName5{get;set;}
                    
    transient public Blob FileBody1{get;set;}
    transient public Blob FileBody2{get;set;}
    transient public Blob FileBody3{get;set;}
    transient public Blob FileBody4{get;set;}
    transient public Blob FileBody5{get;set;}

      Boolean  goFlag = false;
      Boolean  goFlag1 = false;
      Boolean  goFlag2 = false;
      Boolean  goFlag3 = false;
      Boolean  goFlag4 = false;
      Boolean  goFlag5 = false;
      

    public Attachment File1{get
        {
            if(File1 == null){
                File1 = new Attachment();
            }
            return File1;
        }
        set;
    }
    public Attachment File2{get
        {
            if(File2 == null)
            {
                File2 = new Attachment();
            }
            return File2;
        }
    set;}
    public Attachment File3{get
        {
            if(File3 == null)
            {
                File3 = new Attachment();
            }
            return File3;
        }    
    set;}
    public Attachment File4{get
        {
            if(File4 == null)
            {
                File4 = new Attachment();
            }
            return File4;
        }    
    set;}
    public Attachment File5{get
        {
            if(File5 == null)
            {
                File5 = new Attachment();
            }
            return File5;
        }    
    set;}
    
    public String IdString
    {
        get{return ApexPages.currentPage().getParameters().get('Id');}
        set;
    }
    
    public SendMessage(ApexPages.StandardController controller)
    {
        //AreaValue='d';
        isCheck=false;
        SDisplay=false;
        MDisplay=false;
        //acc=new Account();
        userList=new List<User>();
        accLeftList=new List<MessageEntry>();
        accRightList=new List<MessageEntry>();
        user=new User();
        //acc=new Account();
        mhr=new Message__c();
        
        u=[select UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c from User where Id=:UserInfo.getUserId()];
        
        RegionList=new List<SelectOption>();
        RegionList.add(new SelectOption('0','所有大区'));
        if(u.UserRegion__c == NULL)
        {
            for(Place__c p:[select Id,Name from Place__c where PlaceType__c='Region'])
                RegionList.add(new SelectOption(p.Name,p.Name));
        }
        else
        {
            RegionList.add(new SelectOption(u.UserRegion__c,u.UserRegion__c));
        }
        
        User u=[select FunctionDepartment__c from User where Id=:UserInfo.getUserId()];
        MsgTypeList=new List<SelectOption>();
        //Schema.Describefieldresult mf=Schema.Sobjecttype.Message__c.fields.Type__c;
        //List<Schema.Picklistentry> pf=mf.getPicklistValues();
        //for(Schema.Picklistentry en:pf)
        if(u.FunctionDepartment__c=='Trade Sales'  || u.FunctionDepartment__c=='Trade Functional')
            MsgTypeList.add(new SelectOption('营业信息','营业信息'));
        else if(u.FunctionDepartment__c=='Medical Sales'  ||u.FunctionDepartment__c=='Medical Functional')
           MsgTypeList.add(new SelectOption('医务信息','医务信息'));
        else
        {
            MsgTypeList.add(new SelectOption('营业信息','营业信息'));
            MsgTypeList.add(new SelectOption('医务信息','医务信息'));
        }
        
        channelList=new List<SelectOption>();
        Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Channel__c;
        List<Schema.PicklistEntry> P = F.getPicklistValues();
        channelList.add(new SelectOption('0','ALL'));
        for(Schema.PicklistEntry entry : P)
        {
           channelList.add(new SelectOption(entry.getValue(),entry.getLabel()));//getValue()
        }
        
        outletTypeList=new List<SelectOption>();
        Schema.DescribeFieldResult f2 = Schema.sObjectType.Account.fields.Outlet_Type__c;
        List<Schema.PicklistEntry> P2 = F2.getPicklistValues();
        outletTypeList.add(new SelectOption('0','ALL'));
        for(Schema.PicklistEntry entry : P2)
        {
           outletTypeList.add(new SelectOption(entry.getValue(),entry.getLabel()));
        }
        
        //加载KA条件选项值
        KAAccountList=new List<SelectOption>();
        Schema.DescribeFieldResult KAFiled = Schema.sObjectType.Account.fields.Chain_Customer__c;
        List<Schema.PicklistEntry> KAPickList = KAFiled.getPicklistValues();
        KAAccountList.add(new SelectOption('0','ALL'));
        for(Schema.PicklistEntry entry : KAPickList)
        {
           KAAccountList.add(new SelectOption(entry.getValue(),entry.getLabel()));
        }
        
        if(u.FunctionDepartment__c=='Medical Sales' || u.FunctionDepartment__c=='Medical Functional')
        {
            SDisplay=false;
            MDisplay=true;
        }
        else if(u.FunctionDepartment__c=='Trade Sales'  || u.FunctionDepartment__c=='Trade Functional')
        {
            SDisplay=true;
            MDisplay=false;
        }
        else
        {
            SDisplay=true;
            MDisplay=false;
        }
        
        controlIsDisplay=false;
        if(IdString!=NULL && IdString!='')
        {
            //accRightList=new List<MessageEntry>();
            controlIsDisplay=true;
            mhr=[Select Type__c, StartDate__c,Name, EndDate__c, Content__c From Message__c where Id=:IdString];
            if(mhr.Type__c=='Trade Message' || mhr.Type__c=='门店信息')
            {
                SDisplay=false;
                MDisplay=true;
            }
            if(mhr.Type__c=='Medical Message' || mhr.Type__c=='医务信息')
            {
                SDisplay=false;
                MDisplay=true;
            }
            /*for(MessageRecipient__c r:[select Recipient__c,Status__c,Message__c from MessageRecipient__c where Message__c=:IdString])
            {
                User ut=[select Id,Name from User where Id=:r.Recipient__c and IsActive=true];
                MessageEntry me=new MessageEntry(true,ut);
                accRightList.add(me);
            }*/
        }
        
    }
    
    public List<SelectOption> SubRegionList
    {
        get
        {
            if(SubRegionList==null)
                SubRegionList=new List<SelectOption>();
            else
                SubRegionList.clear();
            
            SubRegionList.add( new SelectOption('0','所有片区'));
            if(u.UserSubRegion__c == NULL)
            {
                for(Place__c p:[select Id,Name from Place__c where PlaceType__c='Sub-region' and Region__r.Name=:RegionValue])
                {
                    SubRegionList.add(new SelectOption(p.Name,P.Name));
                }   
            }
            else
            {
                SubRegionList.add(new SelectOption(u.UserSubRegion__c,u.UserSubRegion__c));
            }
            return SubRegionList;
        }
        set;    
    }
    
    public List<SelectOption> AreaList
    {
        get
        {
            if(AreaList==null)
                AreaList=new List<SelectOption>();
            else
                AreaList.clear();
            
            AreaList.add(new SelectOption('0','所有区域'));
            if(u.UserAreaValue__c==NULL)
            {
                for(Place__c p:[select Id,Name from Place__c where PlaceType__c='Area' and Subregion__r.Name=:SubRegionValue])
                {
                    AreaList.add(new SelectOption(p.Name,P.Name));
                }
            }
            else
            {
                List<String> arr=String.valueOf(u.UserAreaValue__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    for(String s:arr)
                        AreaList.add(new SelectOption(s,s));
                }
            }
            return  AreaList;
        }
        set;
    }
    
     public List<SelectOption> CityList
    {
        get
        {
            if(CityList==null)
                CityList=new List<SelectOption>();
            
            CityList.clear();
            CityList.add(new SelectOption('0','所有城市'));
            if(u.UserCity__c==NULL)
            {
                if(AreaValue != '0' || AreaValue != NULL)
                {
                    for(Place__c p:[select Id,Name from Place__c where PlaceType__c='City' and Area__r.Name=:AreaValue])//AreaValue])
                    {
                        CityList.add(new SelectOption(P.Name,P.Name));
                    }   
                }
            }
            else
            {
                List<String> arr=String.valueOf(u.UserCity__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    for(String s:arr)
                        CityList.add(new SelectOption(s,s));
                }
            }
            return CityList;
        }
       set;
    }
    //或取常用联系人
    public List<MessageContactList__c> GetMessageContactList
    {
        get
        {
            String typeStr='';
            if(IdString==NULL)
                typeStr=MsgTypeValue;
            else
                typeStr=mhr.Type__c;
                
            return [select Id,ContactUser__c,Type__c from MessageContactList__c where OwnerId=:UserInfo.getUserId() and Type__c=:typeStr];
        }
        //set;
    }
    //将常用联系人放入Set
    public Set<Id> GetContactSetList
    {
        get
        {
            if(GetContactSetList==NULL)
                    GetContactSetList=new Set<Id>();
                else
                    GetContactSetList.clear();
                    
            if(GetMessageContactList!=NULL)
            {
                for(MessageContactList__c msg:GetMessageContactList)
                {
                    GetContactSetList.add(msg.ContactUser__c);
                }
            }
            return GetContactSetList;
        }set;
    }
    
    
    public PageReference Searchs()
    {
        errorMsg='';
        //List<MessageEntry> tempList=new List<MessageEntry>();  
        accLeftList.clear();
        String sql='select Id,name from user where id in(select ownerId from account where Active_Status__c=\'正常营业\' ';
        String filter='';
        if(channelValue != NULL && channelValue!='0')
            filter+='Channel__c=\''+channelValue+'\'';
        if(outletTypeValue != NULL && outletTypeValue!='0')
        {
            if(filter.length()>0)
                filter+=' and ';
                   
            filter+=' Outlet_Type__c=\''+outletTypeValue+'\'';
        }
        //KA连锁客户
        if(KAAccountValue != NULL && KAAccountValue!='0')
        {
            if(filter.length()>0)
                filter+=' and ';
                
            filter+=' Chain_Customer__c=\''+KAAccountValue+'\'';//isNC
        }
        
        String city=GetTradeCityFilter();
        if(city !='' || city.length()>0)
        {
            if(filter.length()>0)
                filter+=' and ';
                
            filter+=' ('+city+')';
        }
        
        if(filter.length()>0)
            sql+='and '+filter+') and IsActive=true and FunctionDepartment__c like \'%Trade%\' and Title__c=\'Sales Rep\'';
        else
        {
           
            sql+=') and IsActive=true and FunctionDepartment__c like \'%Trade%\' and Title__c=\'Sales Rep\'';
        }
       
       String str=GetFilter();
        if(str !='' || str.length()>0)
            sql+=' and ('+str+')';
       
       
       // errorMsg=sql;  
       sql+=' order by name asc';  
        List<User> uList=DataBase.query(sql);
        for(User u:uList)
        {
            
          MessageEntry entry=new MessageEntry(false,u);
          accLeftList.add(entry);
        }
        
        for(Integer i=0;i<accRightList.size();i++)
        {
            MessageEntry en=accRightList[i];
            User u=en.u;
            for(Integer j=0;j<accLeftList.size();j++)
            {
                MessageEntry en2=accLeftList[j];
                if(en.u.Id==en2.u.Id)
                {
                    accLeftList.remove(j);
                }
            }
        }
        
       //errorMsg=sql;
        return null;
    }
    public PageReference Searchs2()
    {
        errorMsg='';
        accLeftList.clear();
        String sql='select Id,Name from User where name like \'%'+UserName+'%\'';
        //String filter='';
        //if(user.City!=NULL)
        //    sql+=' and (City__c like \'%'+UserCity+'%\' or CityChn__c like \'%'+UserCity+'%\')';
        
       sql+=' and IsActive=true and FunctionDepartment__c like \'%Medical%\'';
        if(GetFilter() !='' || GetFilter().length()>0)
            sql+=' and ('+GetFilter()+')';
       
       String city=GetMedicalCityFilter();
       if(city !='' || city.length()>0)
            sql+=' and ('+city+')';
       
       User cu=[select Id,name,title__c from User where Id=:UserInfo.getUserId()];
       if(cu.Title__c=='Regional Sales Manager')
            sql+=' and Title__c !=\'Functional\'';
       
       sql+=' order by name asc'; 
        for(User u:DataBase.query(sql))
        {
            MessageEntry entry=new MessageEntry(false,u);
            accLeftList.add(entry);
        }
        
         for(Integer i=0;i<accRightList.size();i++)
        {
            MessageEntry en=accRightList[i];
            User u=en.u;
            for(Integer j=0;j<accLeftList.size();j++)
            {
                MessageEntry en2=accLeftList[j];
                if(en.u.Id==en2.u.Id)
                {
                    accLeftList.remove(j);
                }
            }
        }
        // System.Debug('**********************************************'+sql);
        //errorMsg=sql;
        return null;
    }
    
    public String GetMedicalCityFilter()
    {
        User u=[select UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c from User where Id=:UserInfo.getUserId()];
        
        String Str='';
        if(RegionValue != '0')
        {
            str+=' UserRegion__c=\''+RegionValue+'\'';
        }
        else
        {
            if(u.UserRegion__c!=NULL)
                str+=' UserRegion__c=\''+u.UserRegion__c+'\'';
        }
        if(SubRegionValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' UserSubRegion__c=\''+SubRegionValue+'\'';
        }
        else
        {
            if(u.UserSubRegion__c!=NULL)
            {
                if(Str!='')
                    str+=' and ';
                
                str+=' UserSubRegion__c=\''+u.UserSubRegion__c+'\'';
            }
        }
        
        if(AreaValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' UserAreaValue__c=\''+AreaValue+'\'';
        }
        else
        {
            if(u.UserAreaValue__c!=NULL)
            {
                List<String> arr=String.valueOf(u.UserAreaValue__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    if(Str!='')
                        str+=' and ';
                    String f=''; 
                    
                    for(String s:arr)
                    {
                        if(f!='')
                            f+=' or';
                            
                        f+=' UserAreaValue__c includes(\''+s+'\')';
                    }
                    
                    Str+=' ('+f+')';
                }
            }
        }
        if(CityValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' UserCity__c includes(\''+CityValue+'\')';
        }
        else
        {
            if(u.UserCity__c!=NULL)
            {
                String Cityfilter='';
                List<String> arr=String.valueOf(u.UserCity__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    if(Str!='')
                        str+=' and ';
                    for(String s:arr)
                    {
                        if(Cityfilter!='')
                            Cityfilter+=' or ';
                            
                        Cityfilter+=' UserCity__c includes(\''+s+'\')';
                    }
                    
                    Str+=' ('+Cityfilter+')';
                }
            }
        }
        return Str;
    }
    public String GetTradeCityFilter()
    {
        User u=[select UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c from User where Id=:UserInfo.getUserId()];
        String Str='';
        
        if(RegionValue != '0')
        {
            str+=' OutletRegion__c=\''+RegionValue+'\'';
        }
        else
        {
            if(u.UserRegion__c!=NULL)
                str+=' OutletRegion__c=\''+u.UserRegion__c+'\'';
        }
        if(SubRegionValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' OutletSubRegion__c=\''+SubRegionValue+'\'';
        }
        else
        {
            if(u.UserSubRegion__c!=NULL)
            {
                if(Str!='')
                    str+=' and ';
                str+=' OutletSubRegion__c=\''+u.UserSubRegion__c+'\'';
            }
        }
        if(AreaValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' OutletArea__c=\''+AreaValue+'\'';
        }
        else
        {
            if(u.UserAreaValue__c!=NULL)
            {
                List<String> arr=String.valueOf(u.UserAreaValue__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    if(Str!='')
                        str+=' and ';
                    String f=''; 
                    
                    for(String s:arr)
                    {
                        if(f!='')
                            f+=' or';
                            
                        f+=' OutletArea__c=\''+s+'\'';
                    }
                    
                    Str+=' ('+f+')';
                }
            }
        }
       if(CityValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' City__r.Name=\''+CityValue+'\'';
        }
        else
        {
            if(u.UserCity__c!=NULL)
            {
                List<String> arr=String.valueOf(u.UserCity__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    if(Str!='')
                        str+=' and ';
                    String f=''; 
                    
                    for(String s:arr)
                    {
                        if(f!='')
                            f+=' or';
                            
                        f+=' City__r.Name=\''+s+'\'';
                    }
                    
                    Str+=' ('+f+')';
                }
            }
        }
        
        return Str;
    }
    
    public String GetFilter()
    {
        String filter='';
        User u=[select Id,Name,Title__c,FunctionDepartment__c from User where Id=:UserInfo.getUserId()];
       if(u.Title__c=='Area/District Sales Manager')
       {
         for(User u1:[select Id,Name,Title__c from User where ManagerId=:u.Id])
         {
            if(u1.Title__c!='Sales Rep')
            {
                for(User u2:[select Id,Name,Title__c from User where ManagerId=:u1.Id])
                {
                    
                    if(u2.Title__c=='Sales Rep')
                    {
                        if(filter.length()>0)
                            filter+=' or';
                            
                        filter+=' Id=\''+u2.Id+'\' ';
                    }
                        
                }
            }
            if(u1.Title__c=='Sales Rep')
            {
                if(filter.length()>0)
                    filter+=' or';
                    
                filter+=' Id=\''+u1.Id+'\' ';
            }
         }
       }
       else if(u.Title__c=='Sales Supervisor')
       {
            for(User u2:[select Id,Name,Title__c from User where ManagerId=:u.Id])
            {
                    if(u2.Title__c =='Sales Rep')
                    {
                        if(filter.length()>0)
                            filter+=' or';
                            
                        filter+=' Id=\''+u2.Id+'\' ';
                    }
            }
       }
       
       return filter;
    }
    
    public PageReference OnchageAction()
    {
        if(MsgTypeValue=='营业信息')
        {
            SDisplay=true;
            MDisplay=false;
        }
        else
        {
            SDisplay=false;
            MDisplay=true;
        }
        CityList.clear();
        accLeftList.clear();
        accRightList.clear();
        errorMsg='';
        return null;
    } 
    
    public PageReference onChangeSelectAll()
    {
        for(MessageEntry en:accLeftList)
        {
            en.Ischeck=isCheck;
        }
        
        return null;
    }
    public PageReference onChangeSelectAllRight()
    {
        for(MessageEntry en:accRightList)
        {
            en.Ischeck=isCheck2;
        }
        
        return null;
    }
    public PageReference Add()
    {
        isCheck=false;
        isCheck2=false;
        for(Integer i=0;i<accLeftList.size();i++)
        {
            MessageEntry e=accLeftList[i];
            if(e.Ischeck)
            {
                e.Ischeck=false;
                accRightList.add(e);
                accLeftList.remove(i);
                i=i-1;
            }
        }
        return null;
    }
    
    public PageReference Del()
    {
        isCheck=false;
        isCheck2=false;
        for(Integer i=0;i<accRightList.size();i++)
        {
            MessageEntry e=accRightList[i];
            if(e.Ischeck)
            {
                e.Ischeck=false;
                accLeftList.add(e);
                accRightList.remove(i);
                i=i-1;
            }
        }
        return null;
    }
     public PageReference Next()
    {
        mainErrorMsg='';
        Msg='';
        errorMsg='';
        if(mhr.EndDate__c<System.today() || mhr.StartDate__c<System.today())
        {
            Msg='结束时间和开始时间不能小于今天';
            return null;
        }
        if(mhr.EndDate__c<mhr.StartDate__c)
        {
            mainErrorMsg='';
            errorMsg='';
            Msg='结束时间不能小于开始时间';
            return null;
        }

        List<MessageRecipient__c> listMsg=new List<MessageRecipient__c>();
        for(MessageEntry e:accRightList)
        {
            MessageRecipient__c msg=new MessageRecipient__c(Recipient__c=e.u.Id);
            listMsg.add(msg);
        }
        if(listMsg.size()<=0)
        {
            mainErrorMsg='';
            Msg='';
            errorMsg='请选择收信人';
            return null;
        }
        if(mhr.Name==NULL || mhr.Content__c==NULL || mhr.StartDate__c==NULL || mhr.EndDate__c==NULL)
        {
            errorMsg='';
            Msg='';
            mainErrorMsg='请将必填项填写完整';
            return null;
        }                 
        return Page.SendMessageAddFiles;
    }
    
     public PageReference SendAll()
     {
        if(IdString==NULL || IdString=='')
        {
             try{
                //insert Message History Record
                List<MessageRecipient__c> listMsg=new List<MessageRecipient__c>();
               
                if(accRightList.size()>0)
                {
                    mhr.Type__c=MsgTypeValue;
                    insert mhr;
                    for(MessageEntry e:accRightList)
                    {
                        MessageRecipient__c msg=new MessageRecipient__c(Recipient__c=e.u.Id,Message__c=mhr.Id);
                        listMsg.add(msg);
                    }
                   
                    insert listMsg;               
                }
                
           /*     AlertMsg1='';
                AlertMsg2='';
                AlertMsg3='';
                AlertMsg4='';
                AlertMsg5='';
                
                if(FileBody1!=NULL && FileBody1.size()>300)
                {
                    AlertMsg1='附件不能超过300K';
                    //return null;
                }
                 if(FileBody2!=NULL && FileBody2.size()>300)
                {
                    if(AlertMsg1!='')
                        AlertMsg1+=',第二个附件不能超过300K';
                    else
                        AlertMsg1='第二个附件不能超过300K';  
                    //AlertMsg2='附件不能超过300K';
                    //return null;
                }
                 if(FileBody3!=NULL && FileBody3.size()>300)
                {
                    AlertMsg3='附件不能超过300K';
                    //return null;
                }
                 if(FileBody4!=NULL && FileBody4.size()>300)
                {
                    AlertMsg4='附件不能超过300K';
                    //return null;
                }
                 if(FileBody5!=NULL && FileBody5.size()>300)
                {
                    AlertMsg5='附件不能超过300K';
                    //return null;
                }
                if(AlertMsg1!='' || AlertMsg2!='' || AlertMsg3!='' || AlertMsg4!='' ||AlertMsg5!='')
                {
                    FileBody1=NULL;
                    FileBody2=NULL;
                    FileBody3=NULL;
                    FileBody4=NULL;
                    FileBody5=NULL;
                    return null;
                }*/
                    
                if((FileBody1 != null)||(goFlag == true)){
                    File1.Body = FileBody1;
                    File1.Name = FileName1;
                    File1.ParentId = mhr.Id;
                    File1.OwnerId = UserInfo.getUserId();
                    
                    insert File1;
                }
                if((FileBody2 != null)||(goFlag == true)){
                    File2.Body = FileBody2;
                    File2.Name = FileName2;
                    File2.ParentId = mhr.Id;
                    File2.OwnerId = UserInfo.getUserId();
                    insert File2;
                }
                if((FileBody3 != null)||(goFlag == true)){
                    File3.Body = FileBody3;
                    File3.Name = FileName3;
                    File3.ParentId = mhr.Id;
                    File3.OwnerId = UserInfo.getUserId();
                    insert File3;
                }
                if((FileBody4 != null)||(goFlag == true)){
                    File4.Body = FileBody4;
                    File4.Name = FileName4;
                    File4.ParentId = mhr.Id;
                    File4.OwnerId = UserInfo.getUserId();
                    
                    insert File4;
                } 
               if((FileBody5 != null)||(goFlag == true)){
                    File5.Body = FileBody5;
                    File5.Name = FileName5;
                    File5.ParentId = mhr.Id;
                    File5.OwnerId = UserInfo.getUserId();
                    
                    insert File5;
                }                                      
                PageReference pr=new PageReference('/'+mhr.Id);
                pr.setRedirect(true);
                return pr;
            }
            catch (DmlException e) {
                ApexPages.addMessages(e);
                return null;
             }
        }
        else
        {
            List<MessageRecipient__c> reList=new List<MessageRecipient__c>();
            //delete [select Id from MessageRecipient__c where Message__c=:IdString];
            for(MessageEntry me:accRightList)
            {
                MessageRecipient__c msg=new MessageRecipient__c(Recipient__c=me.u.Id,Message__c=IdString);
                reList.add(msg);
            }
            insert reList;
            PageReference pr=new PageReference('/'+IdString);
            pr.setRedirect(true);
            return pr;
        }
     }
     //加载常用联系人
    public PageReference LoadContactDataAction()
    {
        if(accRightList==NULL)
            accRightList=new List<MessageEntry>();
            
        Set<Id> SetList=new Set<Id>();
        //Set<Id> UserIdSet=new Set<Id>();
        Set<Id> RightUserId=new Set<Id>();
        
        //查找常用联系人列表相对应的用户,剔除现有的右边的值
        Map<Id,User> userList=new Map<Id,User>([select Id,Name from User where Id in: GetContactSetList]);
        //将右边的集合剔除重复
        for(MessageEntry en:accRightList)
        {
            RightUserId.add(en.u.Id);
        }
        
        //添加至右边
        for(MessageContactList__c msg:GetMessageContactList)
        {
            if(!RightUserId.contains(msg.ContactUser__c))
            {
                if(userList.containsKey(msg.ContactUser__c))
                {
                    MessageEntry en=new MessageEntry(false,(User)userList.get(msg.ContactUser__c));
                    accRightList.add(en);
                    SetList.add(msg.ContactUser__c); 
                }
            }
        }
        //删除左边
        if(accLeftList!=NULL && accLeftList.size()>0)
        {
            for(Integer i=0;i<accLeftList.size();i++)
            {
                MessageEntry msg=accLeftList[i];
                if(msg!=NULL)
                {
                    if(SetList.contains(msg.u.Id))
                    {
                        accLeftList.remove(i);
                        i=i-1;
                    }
                }
            }
        }
        return null;
    }
    //添加常用联系人
    public PageReference AddToContactListAction()
    {
        //set GetContactSetList(ID)   GetMessageContactList
        String typeStr='';
        //Set<Id> RightUserIdList=new Set<Id>();
        List<MessageContactList__c> AddContactList=new List<MessageContactList__c>();
        if(accRightList.size()>0)
        {
            if(IdString==NULL)//MsgTypeValue
                typeStr=MsgTypeValue;
            else
                typeStr=mhr.Type__c;
                
            //先删除
            delete GetMessageContactList;
            
            for(MessageEntry en:accRightList)
            {
                MessageContactList__c msg=new MessageContactList__c(ContactUser__c=en.u.Id,Type__c=typeStr);
                AddContactList.add(msg);
            }
            
            //删除的
            /*for(Id uid:GetContactSetList)
            {
                if(!RightUserIdList.contains(uid))
                {
                    DeleteUserIdList.add(uid);
                }
            }*/
        }
        
        if(AddContactList.size()>0)
            insert AddContactList;
        
        return null; 
    }
    //清空常用联系人
    public PageReference ClearContactListAction()
    {
        //清空数据
        //List<MessageContactList__c> msgList=[select Id from MessageContactList__c 
        //                                   where OwnerId=:UserInfo.getUserId() and Type__c=:MsgTypeValue];
                                             
        for(Integer i=0;i<accRightList.size();i++)
        {
            MessageEntry en=accRightList[i];
            if(GetContactSetList.contains(en.u.Id))
            {
                accRightList.remove(i);
                accLeftList.add(en);
                i=i-1;
            }
        }
        
        //清空列表
        delete GetMessageContactList;
        return null;
    }
    
    public PageReference Cancel()
    {
        
        PageReference pr=new PageReference('/apex/ViewMessageData');
        pr.setRedirect(true);
        return pr;
    }
    
    public PageReference Before()
    {
        return Page.SendMessageList;
    }
    
    static testmethod void Test()
    {
        Place__c regs=new Place__c(PlaceType__c='Region',Name='华南区');
        insert regs;
        Place__c subregs=new Place__c(PlaceType__c='Sub-region',Name='华南一区',Region__c=regs.Id);
        insert subregs;
        Place__c areas=new Place__c(PlaceType__c='PlaceType__c',Name='广州区域',Region__c=regs.Id,Subregion__c=subregs.Id);
        insert areas;
        Place__c citys=new Place__c(PlaceType__c='City',Name='广州',Region__c=regs.Id,Subregion__c=subregs.Id,Area__c=areas.Id);
        insert citys;
            
        List<Profile> pl = [select id from profile where Name='System Administrator' or name = '系统管理员' limit 1];
        
        Profile p=pl[0];
        User u = new User(alias = 'standtss', email='standarduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',Title__c='Area/District Sales Manager',
        localesidkey='en_US', profileid = p.Id,UserCity__c='广州',IsActive=true,
        UserAreaValue__c='广州区域',UserSubRegion__c='华南一区',UserRegion__c='华南区',
        timezonesidkey='America/Los_Angeles', username='standardusers@testorg.com');
        insert u;
        
        User test = new User(alias = 'standtss', email='str@testorgss.com',Title__c='Sales Rep',ManagerId=u.Id,
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,UserCity__c='广州',FunctionDepartment__c='Medical Sales',
        UserAreaValue__c='广州区域',UserSubRegion__c='华南一区',UserRegion__c='华南区',IsActive=true,
        timezonesidkey='America/Los_Angeles', username='strs@testorg.com');
        insert test;
        
         Account acc=new Account();
         acc.Name='test';
         acc.Channel__c='特大型综合超市';
         acc.Outlet_Type__c='全国重点客户';
         acc.Contact__c='aaa';
         acc.No_of_checkout__c=22;
         acc.ContactPhoneNumber__c='1234567456';
         acc.City__c=citys.Id;
         acc.OwnerId=u.Id;
         insert acc;
        
        System.runAs(u)
        {
            Message__c m=new Message__c();
            ApexPages.StandardController sc = new ApexPages.StandardController(m);
            
            SendMessage send=new SendMessage(sc);
            send.mhr.Type__c='营业信息';
            send.OnchageAction();
            //send.SubRegionList=null;
           // send.AreaList=null;
            send.channelValue='特大型综合超市';
            send.outletTypeValue='全国重点客户';
            send.RegionValue='华南区';
            send.SubRegionValue='华南一区';
            send.AreaValue='广州区域';
            
            List<SelectOption> subss=send.SubRegionList;
            List<SelectOption> awrea=send.AreaList;
            List<SelectOption> cwity=send.CityList;
            send.accRightList.add(new MessageEntry(false,test));
            send.Searchs();
          //  send.onChangeSelectAll();
            send.Add();
            send.Del();
            send.mhr.Name='test';
            send.mhr.Content__c='test';
            send.mhr.StartDate__c=Date.today();
            send.mhr.EndDate__c=Date.today();           
            //send.Searchs();
            system.assert(send.File1 != null);
            system.assert(send.File2 != null);
            system.assert(send.File3 != null);
            system.assert(send.File4 != null);
            system.assert(send.File5 != null);            
            send.Next();         
            send.goFlag = true;
            Attachment ment = new Attachment();           
            send.File1 =ment;          
            send.SendAll();
            send.Cancel();
            
            //SendMessage send2=new SendMessage(sc);
            //send2.IdString=send.mhr.Id;
            
        }
       
        User u2 = new User(alias='standtss', email='standaerduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testeing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,FunctionDepartment__c='Medical Sales',IsActive=true,
        timezonesidkey='America/Los_Angeles', username='staendardusers@testorg.com');
        insert u2;
        System.runAs(u2)
        {
            Message__c m=new Message__c();
            ApexPages.StandardController sc = new ApexPages.StandardController(m);
            
            SendMessage send=new SendMessage(sc);
            List<SelectOption> t=new List<SelectOption>();
            t.add(new SelectOption('华南区','华南区'));
            send.SubRegionList=t;
            
             List<SelectOption> t2=new List<SelectOption>();
            t2.add(new SelectOption('广州区域','广州区域'));
            send.AreaList=t2; 
            
            send.mhr.Type__c='医务信息';
            send.OnchageAction();
           // send.user.Username='luo';
            send.RegionValue='华南区';
            send.SubRegionValue='华南一区';
            send.AreaValue='广州区域';
            List<SelectOption> sub=send.SubRegionList;
            List<SelectOption> area=send.AreaList;
            List<SelectOption> city=send.CityList;
            send.accRightList.add(new MessageEntry(true,test));          
            send.Searchs2();           
            send.Next();       
                       
            send.SendAll();
            send.Cancel();
            
            
        }
        
        User u3 = new User(alias='standtss', email='aerduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testeing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,FunctionDepartment__c='Trade Sales',IsActive=true,
        timezonesidkey='America/Los_Angeles', username='rdusers@testorg.com');
        insert u3;
        System.runAs(u3)
        {
            Message__c m=new Message__c();
            ApexPages.StandardController sc = new ApexPages.StandardController(m);
            
            SendMessage send=new SendMessage(sc);
             List<SelectOption> t=new List<SelectOption>();
            t.add(new SelectOption('华南一区','华南一区'));
            send.SubRegionList=t; 
            
            List<SelectOption> t2=new List<SelectOption>();
            t2.add(new SelectOption('广州区域','广州区域'));
            send.AreaList=t2;
            
            
            send.mhr.Type__c='营业信息';
            send.OnchageAction();
            send.Searchs();
            MessageEntry en=new MessageEntry(true,u2);
            MessageEntry en2=new MessageEntry(true,u3);
            MessageEntry en3=new MessageEntry(true,test);
            send.accLeftList.add(new MessageEntry(true,u2));
            send.accLeftList.add(en2);
            send.Add();
            send.accRightList.add(en);
            send.accRightList.add(en2);
            send.accRightList.add(new MessageEntry(false,test));
            send.Del();
            send.onChangeSelectAll();
            send.onChangeSelectAllRight();
        }
         User u4 = new User(alias='standtss', email='standaerduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testeing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,FunctionDepartment__c='Medical Sales',IsActive=true,
        timezonesidkey='America/Los_Angeles',UserSubRegion__c='华南一区',UserRegion__c='华南区',UserAreaValue__c='广州区域',
        UserCity__c='广州', username='stusers@testorg.com');
        insert u4;
        System.runAs(u4)
        {
            Message__c m=new Message__c();
            ApexPages.StandardController sc = new ApexPages.StandardController(m);
            
            SendMessage send=new SendMessage(sc);
            List<SelectOption> t=new List<SelectOption>();
            t.add(new SelectOption('华南区','华南区'));
            send.SubRegionList=t;
            
             List<SelectOption> t2=new List<SelectOption>();
            t2.add(new SelectOption('广州区域','广州区域'));
            send.AreaList=t2; 
            
            send.mhr.Type__c='医务信息';
            send.OnchageAction();
           // send.user.Username='luo';
          //  send.RegionValue='华南区';
          //  send.SubRegionValue='华南一区';
           // send.AreaValue='广州区域';
            List<SelectOption> sub=send.SubRegionList;
            List<SelectOption> area=send.AreaList;
            List<SelectOption> city=send.CityList;
            send.accRightList.add(new MessageEntry(true,test));          
            send.Searchs2();           
            send.Next();       
                       
            send.SendAll();
            send.Cancel();
            
            
        }
       
    }
    
}